package socket;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client1 {
    private Socket socket;
    public Client1() {
        try {
            System.out.println("正在连接服务端...");
            socket = new Socket("localhost",8088);
            System.out.println("与服务端建立连接！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start() {
        Client1.ServerHandler handler = new Client1.ServerHandler();
        Thread t = new Thread(handler);
        t.setDaemon(true);//守护线程
        t.start();
        try (PrintWriter pw = new PrintWriter(
                new BufferedWriter(
                        new OutputStreamWriter(
                                socket.getOutputStream(),"UTF-8"
                        )
                ),true
        );
        ){
            Scanner san = new Scanner(System.in);
            System.out.println("请开始输入内容，单独输入exit退出");
            while(true) {
                String line = san.nextLine();
                if ("exit".equals(line)) {
                    System.out.println("已退出");
                    break;
                }
                pw.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private class ServerHandler implements Runnable{
        public void run(){
            try(
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(
                                    socket.getInputStream(),"UTF-8"
                            )
                    );
            ){
                String line;
                while((line = br.readLine())!=null){
                    System.out.println(line);
                }
            }catch(IOException e){
            }
        }
    }
    public static void main(String[] args) {
        Client1 client = new Client1();
        client.start();
    }
}
